//database init
pool = require('../lib/pool');

//parse the sql 
exports.parse = function(req,res){
	
	if(req.path[0]){
		var sql = req.path[0];
		sql = sql.replace(/%20/g,' ').replace(/%3E/g,'>').replace(/%3C/g,'<').replace(/%27/g,'\'').replace(/%22/g,'"');
		
		while(sql.indexOf('  ')!=-1){
			sql = sql.replace('  ',' ');	
		}
		var params = sql.split(' '); 
		var k=0;
		var len = params.length;
		var arr = {};
		while(k<len){
			if(params[k]=='group'){
				arr[''+params[k]+' '+params[k+1]] = params[k+2];
				k+=1;
			}else if(params[k]=='order'){
				arr[''+params[k]+' '+params[k+1]] = params[k+2]+' '+params[k+3];
				k+=2;
			}else{
				arr[''+params[k]] = params[k+1];
			}	
			k+=2;
		}
	}
	vdb_query(sql.split('limit')[0],arr,res);
};

var vdb_query = function(sql,params,res){
	cnt=0;
	data = [];
	for(var k in pool.connections){
		
		var tmp_sql = sql;
		tmp_sql = tmp_sql.replace('from',',\''+pool.pool[k].db+'\' db from');
		tmp_sql = tmp_sql.replace(params.from,pool.pool[k].db+'.'+params.from);
		
		pool.connections[k].query(tmp_sql,function(err,result){
			if(err){
				event.emit('queryFinish',[],res,params);
			}else{
				event.emit('queryFinish',result,res,params);
			}
			
		});
		
	}
};
//event 
var events = require('events');
var event = new events.EventEmitter();
var cnt=0;
var data = [];
event.on('queryFinish',function(rs,res,params){
	cnt++;
	data=data.concat(rs);
	if(cnt==pool.pool.length){
		if(params['order by']!=undefined){
			//field => f , type => t
			var f = params['order by'].split(' ')[0];
			var t = params['order by'].split(' ')[1];
			data.sort(function(a,b){
				if(t=='asc'){
					return a[f]>b[f];
				}
				if(t=='desc'){
					return a[f]<b[f];
				}
			});
		}
		if(params['limit']!=undefined){
			if(params['limit'].indexOf(',')!=-1){
				
				data = data.slice(params['limit'].split(',')[0],1*params['limit'].split(',')[0]+1*params['limit'].split(',')[1]);
			}else{
				
				data = data.slice(0,params['limit']);
			}
		}
		res.end(JSON.stringify(data));
	}
	
});
